from django.http import JsonResponse
from app.models import User
import json
import jwt
import time


# 登录
def login(req):
    if req.method == 'POST':
        data = req.body
        da = json.loads(req.body)
        print(da)
        d = {
            'exp': time.time() + 30000,
            'iat': time.time(),
            'iss': 'Issuer',
            'data': {
                'username': da["phone"],
                'timestamp': time.time()
            }
        }
        jwt_encode = jwt.encode(d, data, algorithm="HS256")
        try:
            li = list(User.objects.filter(phone=da["phone"]).values())[0]

            if da["password"] == li["password"]:
                User.objects.filter(phone=da["phone"]).update(token=jwt_encode, token_end=d["exp"])
                tokens = list(User.objects.filter(phone=da["phone"]).values("token"))
                lia = list(User.objects.filter(phone=da["phone"]).values('id', "name", "role__role_name", "phone", "sex",
                                                                         "password"))[0]
                # lia["role"] = json.loads(lia["role"])
                return JsonResponse({"code": 200, "message": "登陆成功", "data": {"token": tokens[0]["token"],
                                                                              "userInfo": lia}})
            elif da["password"] != li["password"]:
                return JsonResponse({"code": 401, "message": "密码错误"})

        except IndexError:
            return JsonResponse({"code": 400, "message": "没有找到该用户"})
        return JsonResponse({"code": 500, "message": "服务端错误"})
